package com.changgou.seckill.monitor;

import com.alibaba.fastjson.JSONObject;
import com.changgou.seckill.config.SeckillStatus;
import com.changgou.seckill.dao.SeckillGoodsMapper;
import com.changgou.seckill.dao.SeckillOrderMapper;
import com.changgou.seckill.pojo.SeckillGoods;
import com.changgou.seckill.pojo.SeckillOrder;
import com.changgou.util.IdWorker;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * @ClassName: SeckillOrderListener
 * @Author: ZWJ
 * @Date: 2020-09-11 20:11
 * @Synopsis: Null
 **/
@Component
public class SeckillOrderListener {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private IdWorker idWorker;
    @Autowired
    private SeckillOrderMapper seckillOrderMapper;
    @Autowired
    private SeckillGoodsMapper seckillGoodsMapper;
    //新增秒杀订单--抢单（实现下单操作，并将订单存入到Redis缓存）
    @RabbitListener(queues = "seckillOrderQueue")
    public void addSecKillOrder(String msg){
         //接受队列的信息，将队列信息转成javabean
        SeckillStatus seckillStatus = JSONObject.parseObject(msg, SeckillStatus.class);
        //获取用户名
        String username = seckillStatus.getUsername();
        //将队列中的队列值取出来（利用redis中list队列的特性解决超卖问题）
        Object seckillGoodsStockQueue = redisTemplate.boundListOps("SeckillGoodsStocKQueue_"
                + seckillStatus.getGoodsId()).rightPop();
        if (seckillGoodsStockQueue==null){
            //删除排队信息
            stringRedisTemplate.delete("SeckillStatus_"+username);
            //清理排队次数消息
            redisTemplate.delete("UserQueueCount_" + username);
            return;
        }

        //判断是否有其他的订单未支付
        Object order = stringRedisTemplate.boundHashOps("SeckillOrder").get(username);
        SeckillStatus seckillStatus1 = JSONObject.parseObject(order.toString(), SeckillStatus.class);
        if (order!=null&&seckillStatus1.getStatus().equals("0")){
        //有未支付的订单
            SeckillOrder seckillOrder1 = JSONObject.parseObject(order.toString(), SeckillOrder.class);
            //修改排队状态
            seckillStatus.setStatus(3);
            //将状态保存daoredis
            String jsonString = JSONObject.toJSONString(seckillStatus);
            stringRedisTemplate.boundValueOps("SeckillStatus_"+username).set(jsonString);
            return;
        }
        //商品的时间段
        String time = seckillStatus.getTime();
        //商品的id
        String goodsId = seckillStatus.getGoodsId();
        //获取商品的详细信息
        SeckillGoods seckillGoods = (SeckillGoods)redisTemplate.boundHashOps("SeckillGoods_" + time).get(goodsId);
        if (seckillGoods==null||seckillGoods.getStockCount()<=0){
            //删除排队信息
            stringRedisTemplate.delete("SeckillStatus_"+username);
            //清理排队次数消息
            redisTemplate.delete("UserQueueCount_" + username);
            return;
        }
        //商品开始秒杀的时间
        Date startTime = seckillGoods.getStartTime();
        //商品秒杀结束时间
        Date endTime = seckillGoods.getEndTime();
        //现在时间
        Date date=new Date();
        if (startTime.getTime()>date.getTime()){
            //秒杀还未开始
            //删除排队信息
            stringRedisTemplate.delete("SeckillStatus_"+username);
            //清理排队次数消息
            redisTemplate.delete("UserQueueCount_" + username);
            return;
        }
        if (endTime.getTime()<date.getTime()){
            //秒杀已经结束
            //删除排队信息
            stringRedisTemplate.delete("SeckillStatus_"+username);
            //清理排队次数消息
            redisTemplate.delete("UserQueueCount_" + username);
            return;
        }
        //补充订单数据
        SeckillOrder seckillOrder=new SeckillOrder();
        //订单id
        seckillOrder.setId("Order"+ idWorker.nextId());
        //商品的id
        seckillOrder.setSeckillId(seckillStatus.getGoodsId());
        //支付金额
        seckillOrder.setMoney(String.valueOf(seckillGoods.getCostPrice()));
        //用户
        seckillOrder.setUserId(username);
        //创建时间
        seckillOrder.setCreateTime(new Date());
        //支付状态（未支付）
        seckillOrder.setStatus("0");
        //将订单进行保存
        String orderstring = JSONObject.toJSONString(seckillOrder);
        //将订单保存到redis
        stringRedisTemplate.boundHashOps("SeckillOrder").put(username,orderstring);

        //进行下单，对排队状态进行修改
        seckillStatus.setStatus(2);  //修改秒杀状态（下单成功但未支付）
        //应付金额
        seckillStatus.setMoney(Float.valueOf(seckillGoods.getCostPrice()+""));
        //订单号
        seckillStatus.setOrderId(seckillOrder.getId());
        String statusString = JSONObject.toJSONString(seckillStatus);
        //将排队的状态保存redis中
        stringRedisTemplate.boundValueOps("SeckillStatus_"+username).set(statusString);

        //计数器递减（-1之后将减1之后的结果返回）
        Long seckillGoodsStockCount1 = redisTemplate.boundHashOps("SeckillGoodsStockCount").increment(goodsId, -1);
        //对商品的库存进行扣减
        seckillGoods.setStockCount(seckillGoodsStockCount1.intValue());
        //扣减库存后更新数据库
       updateStockCount(seckillGoods,time);
    }
    //扣减库存,更新数据库
    private void updateStockCount(SeckillGoods seckillGoods,String time){
        if(seckillGoods.getStockCount()<=0){
            //将商品数据同步到Mysql中
            seckillGoodsMapper.updateByPrimaryKeySelective(seckillGoods);
            //将redis中商品数据更新
            redisTemplate.boundHashOps("SeckillGoods_"+time).put(seckillGoods.getId(),seckillGoods);
        }else {
            //将商品进行更新
            redisTemplate.boundHashOps("SeckillGoods_"+time).put(seckillGoods.getId(),seckillGoods);
        }
    }
}
